<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\goods;
use DB;
use App\Http\Requests\GoodsPostRequest;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class CartController extends Controller
{   
 
   //前台加入购物车操作
   public function insert(Request $request)
   {    
        //判断用户是否登录
        if(empty(session('id'))){
          echo 0 ;
          die;
        }
        

        // dd($request->all());
        //提取数据
        $data = $request->only('id','num');

        //检测当前商品是否已经存在于购物车中
        if($this->checkcart($data['id']))
        {
            //存在
            $goods = session('cart');
            foreach($goods as $k => $v){
              if($v['id'] == $data['id']){
                $goods[$k]['num'] += $data['num'];
              }
            }
            //重新存入购物车
            session(['cart'=>$goods]);
        }else{
            //不存在
            //将当前数据压入session中
            $request->session()->push('cart',$data);
        }
        // dd($data);
        //添加完成跳转到购物车列表
        // return redirect('/cart/index');
        echo 1;
   }

  private function checkcart($id)
  {
      //读取购物车信息
      $goods = session('cart');
      //检测购物车如果为空返回false
      if(empty($goods)){
          return false;
      }

      //有数据
      foreach ($goods as $k => $v) {
        if($v['id'] == $id){
            //商品存在
            return true;
        }       
      }
      //商品不在购物车中
      return false; 
  }



   //购物车列表
  public function index()
  {
      $goods = session('cart');
      //根据购物车中的商品ID 查询
      $data = [];
      if(!empty($goods)){
        foreach($goods as $k => $v){
          $tmp = Goods::find($v['id']);
          $tmp['num'] = $v['num'];
          $data[] = $tmp;
        }
      }
      // dd($data);
      //解析模板分配变量
      return view('home.cart.cart',['carts'=>$data]);
  }

  //清空购物车
  public function clear(Request $request)
  {
      $request->session()->flush();
  }

  //删除购物车的商品
  public function delete(Request $request)
  {
      //获取删除的商品id
      $id = $request->input('id');
      //获取购物车中的商品
      $data = session('cart');
      //遍历
      foreach ($data as $k => $v) {
        if($v['id'] == $id){
          unset($data[$k]);
        }
      }
      session(['cart'=>$data]);
      //因为session没有返回值所有手动echo一个
      echo 1;
  }

}
